var _excluded = ["replace"];
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { DownOutlined } from '@ant-design/icons';
import { Affix, Badge, Divider, Dropdown, Tooltip } from 'antd';
import React, { useLayoutEffect, useRef } from 'react';
import { BaseIcon, compHoc, iup, IUPComponent, useDevState, useRefCallback, useResize, useUpdateEffect } from "../../util";
import { Button } from "../antd/Button";
import { handleClick } from "./bridge";
import { ButtonEnum } from "./enums";
import { getToolBarButton } from "./registerButton";
import "./index.less";
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
export { candidateButtons } from "./candidate";
export { ButtonEnum };
iup.registerExternal({
  getRegisterButton: getToolBarButton
});
var menuButtonProps = {
  type: 'text',
  size: 'small'
};
var getSize = function getSize(size) {
  return size ? size === 'simple' ? 'middle' : size : 'middle';
};
function SpaceFlex() {
  return /*#__PURE__*/_jsx("div", {
    className: "space-flex",
    style: {
      flex: 1
    }
  });
}
function UserComponent(_ref) {
  var toolbar = _ref.toolbar,
    children = _ref.children,
    uid = _ref.uid,
    type = _ref.type;
  var _toolbar$calcButtonPr = toolbar.calcButtonProps(children),
    hidden = _toolbar$calcButtonPr.hidden,
    disabled = _toolbar$calcButtonPr.disabled;
  return /*#__PURE__*/_jsx("div", {
    "data-cid": uid,
    className: "user-component",
    style: {
      marginRight: "".concat(type === 'link' ? 8 : 0, "px")
    },
    children: /*#__PURE__*/React.isValidElement(children) ? /*#__PURE__*/React.cloneElement(children, {
      disabled: disabled,
      hidden: hidden
    }) : children
  });
}
function createIcon(icon) {
  var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  if (icon === undefined) {
    icon = 'ApiOutlined';
  }
  if (!icon) return null;
  if (iup.isString(icon)) {
    return /*#__PURE__*/React.createElement(BaseIcon[icon] || BaseIcon['ApiOutlined'], props);
  } else {
    return /*#__PURE__*/React.cloneElement(icon, _objectSpread(_objectSpread({}, props), {}, {
      style: _objectSpread(_objectSpread({}, icon.props.style), props.style)
    }));
  }
}
var dropStyle = {
  padding: '5px 12px',
  height: 'auto',
  minHeight: 24,
  minWidth: 90,
  width: '100%',
  textAlign: 'left'
};
var getMenuItems = function getMenuItems(toolbar, menuArray) {
  var items = [];
  menuArray.forEach(function (menu, index) {
    var button = toolbar.format(menu.button || menu);
    if (button.type === 'divider') {
      items.push({
        key: button.id,
        label: /*#__PURE__*/_jsx(Divider, {
          type: "horizontal",
          style: {
            margin: '5px 0'
          }
        })
      });
      return;
    }
    if (button.type === 'userComponent' || /*#__PURE__*/React.isValidElement(button)) {
      var tmp = button.text || button;
      var _toolbar$calcButtonPr2 = toolbar.calcButtonProps(tmp),
        _hidden = _toolbar$calcButtonPr2.hidden,
        _disabled = _toolbar$calcButtonPr2.disabled;
      items.push({
        key: button.id || "user_".concat(index),
        label: /*#__PURE__*/_jsx("div", {
          onClick: function onClick(e) {
            return iup.stopPropagation(e);
          },
          style: {
            padding: '5px 12px'
          },
          children: /*#__PURE__*/React.isValidElement(tmp) ? /*#__PURE__*/React.cloneElement(tmp, {
            disabled: _disabled,
            hidden: _hidden
          }) : tmp
        })
      });
      return;
    }
    var _toolbar$calcButtonPr3 = toolbar.calcButtonProps(button),
      hidden = _toolbar$calcButtonPr3.hidden,
      text = _toolbar$calcButtonPr3.text,
      disabled = _toolbar$calcButtonPr3.disabled,
      size = _toolbar$calcButtonPr3.size;
    if (hidden) {
      return;
    }
    if (button.children) {
      items.push({
        key: button.id,
        disabled: disabled,
        label: text,
        popupClassName: iup.classNames('iup-toolbar-submenu', size),
        children: getMenuItems(toolbar, button.children)
      });
    } else {
      items.push({
        key: button.id,
        disabled: disabled,
        label: /*#__PURE__*/_jsx(ToolBarItem, {
          style: dropStyle,
          button: button,
          toolbar: toolbar,
          isMenuItem: true
        }, button.id)
      });
    }
  });
  return items;
};
function FoldMenu(_ref2) {
  var _btnProps$style;
  var toolbar = _ref2.toolbar;
  var elRef = useRef();
  var initDropdown = useRefCallback(function () {
    var tbEl = elRef.current.parentElement;
    if (!tbEl) {
      return;
    }
    if (!toolbar.btnWidths) {
      toolbar.btnWidths = {}; // 缓存button的宽度
    }
    var tbOffsetWidth = tbEl.offsetWidth;
    var tbScrollWidth = tbEl.scrollWidth;
    var dropdown = [];
    if (tbOffsetWidth < tbScrollWidth) {
      var _tbEl$querySelector;
      //  左右padding + 更多按钮宽度
      var tmpWidth = (((_tbEl$querySelector = tbEl.querySelector('.iup-btn-more')) === null || _tbEl$querySelector === void 0 ? void 0 : _tbEl$querySelector.offsetWidth) || (['text', 'link'].includes(toolbar.props.type) ? 48 : 82)) + (parseFloat(iup.getStyle(tbEl, 'paddingLeft')) || 0) + (parseFloat(iup.getStyle(tbEl, 'paddingRight')) || 0);
      tbEl.childNodes.forEach(function (child) {
        var _child$getAttribute, _child$getAttribute2;
        var itemId = ((_child$getAttribute = child.getAttribute) === null || _child$getAttribute === void 0 ? void 0 : _child$getAttribute.call(child, 'id')) || ((_child$getAttribute2 = child.getAttribute) === null || _child$getAttribute2 === void 0 ? void 0 : _child$getAttribute2.call(child, 'data-cid'));
        var childOffsetWidth = toolbar.btnWidths[itemId];
        if (iup.isNullOrEmpty(childOffsetWidth)) {
          childOffsetWidth = child.offsetWidth + (parseFloat(iup.getStyle(child, 'marginLeft')) || 0) + (parseFloat(iup.getStyle(child, 'marginRight')) || 0);
          itemId && (toolbar.btnWidths[itemId] = childOffsetWidth);
        }
        tmpWidth += childOffsetWidth;
        if (tmpWidth > tbOffsetWidth && itemId) {
          dropdown.push({
            button: function () {
              if (itemId.indexOf('_divider_') === 0) {
                return {
                  type: 'divider',
                  id: itemId
                };
              }
              if (itemId.indexOf('_user_component_') === 0) {
                var _toolbar$userComponen;
                return {
                  type: 'userComponent',
                  id: itemId,
                  text: (_toolbar$userComponen = toolbar.userComponents) === null || _toolbar$userComponen === void 0 ? void 0 : _toolbar$userComponen[itemId]
                };
              }
              return toolbar.findItem(itemId);
            }(),
            itemId: itemId,
            width: childOffsetWidth
          });
        }
      });
    }
    if (toolbar.state.dropdown.length !== dropdown.length) {
      toolbar.setState(function (prev) {
        return _objectSpread(_objectSpread({}, prev), {}, {
          dropdown: dropdown
        });
      });
    }
  });
  useLayoutEffect(function () {
    toolbar.btnWidths = {};
    initDropdown();
  }, [toolbar.state.resize]);
  var getParentEl = useRefCallback(function () {
    return elRef.current.parentElement;
  });
  useResize(function () {
    toolbar.setState(function (prev) {
      return _objectSpread(_objectSpread({}, prev), {}, {
        dropdown: [],
        resize: {}
      });
    });
  }, getParentEl);
  useUpdateEffect(function () {
    toolbar.setState(function (prev) {
      return _objectSpread(_objectSpread({}, prev), {}, {
        dropdown: [],
        resize: {}
      });
    });
  }, [toolbar.dev.size, toolbar.dev.type, toolbar.dev.buttons]);
  var btnProps = _objectSpread(_objectSpread({}, menuButtonProps), {}, {
    size: getSize(toolbar.dev.size),
    type: toolbar.dev.type || 'default'
  });
  if (btnProps.size === 'small' && ['link', 'text'].includes(btnProps.type) && !((_btnProps$style = btnProps.style) !== null && _btnProps$style !== void 0 && _btnProps$style.padding)) {
    btnProps.style = _objectSpread(_objectSpread({}, btnProps.style), {}, {
      padding: 0
    });
  }
  var showMore = !!toolbar.state.dropdown.length;
  return /*#__PURE__*/_jsx("span", {
    ref: elRef,
    style: {
      display: showMore ? 'flex' : 'none'
    },
    children: showMore && (iup.isFunction(toolbar.dev.moreIcon) ? toolbar.dev.moreIcon(toolbar.state.dropdown.map(function (_ref3, idx) {
      var button = _ref3.button;
      return toolbar.format(button, idx);
    })) : /*#__PURE__*/_jsx(Dropdown, {
      menu: {
        items: getMenuItems(toolbar, toolbar.state.dropdown),
        className: iup.classNames('iup-toolbar-menu', getSize(toolbar.dev.size))
      },
      onOpenChange: toolbar.onOpenChange({}),
      children: /*#__PURE__*/_jsxs(Button, _objectSpread(_objectSpread({}, btnProps), {}, {
        className: "iup-btn-more",
        children: ["\u66F4\u591A", toolbar.dev.moreIcon || createIcon('DownOutlined', {
          style: toolbar.dev.iconColor ? {
            color: toolbar.dev.iconColor,
            marginLeft: 5
          } : {
            marginLeft: 5
          }
        })]
      }))
    }))
  });
}
function TooltipButton(_ref4) {
  var title = _ref4.title,
    buttonProps = _ref4.buttonProps,
    outRef = _ref4.outRef,
    badgeText = _ref4.badgeText;
  var render = function render() {
    if (badgeText) {
      return /*#__PURE__*/_jsx(Badge, {
        count: badgeText,
        size: "small",
        styles: {
          root: {
            color: 'inherit'
          }
        },
        offset: [-10, 2],
        children: /*#__PURE__*/_jsx(Button, _objectSpread(_objectSpread({}, buttonProps), {}, {
          ref: outRef
        }))
      });
    }
    return /*#__PURE__*/_jsx(Button, _objectSpread(_objectSpread({}, buttonProps), {}, {
      ref: outRef
    }));
  };
  return title ? /*#__PURE__*/_jsx(Tooltip, {
    title: title,
    children: render()
  }) : render();
}
var ToolBarItem = /*#__PURE__*/function (_IUPComponent) {
  _inherits(ToolBarItem, _IUPComponent);
  var _super = _createSuper(ToolBarItem);
  function ToolBarItem(props) {
    var _this;
    _classCallCheck(this, ToolBarItem);
    _this = _super.call(this, props);
    _this.state = {
      defaultBadge: undefined
    };
    return _this;
  }
  _createClass(ToolBarItem, [{
    key: "componentDidMount",
    value: function () {
      var _componentDidMount = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
        var _this$props$toolbar;
        return _regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              (_this$props$toolbar = this.props.toolbar) === null || _this$props$toolbar === void 0 || _this$props$toolbar.addItemMap(this);
            case 1:
            case "end":
              return _context.stop();
          }
        }, _callee, this);
      }));
      function componentDidMount() {
        return _componentDidMount.apply(this, arguments);
      }
      return componentDidMount;
    }()
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var _this$props$toolbar2;
      (_this$props$toolbar2 = this.props.toolbar) === null || _this$props$toolbar2 === void 0 || _this$props$toolbar2.deleteItemMap(this);
    }
  }, {
    key: "isSimpleButton",
    value: function isSimpleButton() {
      var _this$props = this.props,
        toolbar = _this$props.toolbar,
        button = _this$props.button,
        _this$props$isMenuIte = _this$props.isMenuItem,
        isMenuItem = _this$props$isMenuIte === void 0 ? false : _this$props$isMenuIte;
      return !isMenuItem && (toolbar.dev.size === 'simple' || button.simple);
    }
  }, {
    key: "getApi",
    value: function getApi() {
      var _this$outRef$current,
        _this2 = this;
      return _objectSpread(_objectSpread({}, (_this$outRef$current = this.outRef.current) === null || _this$outRef$current === void 0 ? void 0 : _this$outRef$current.getApi()), {}, {
        setState: function setState() {
          return _this2.setState(arguments.length <= 0 ? undefined : arguments[0], arguments.length <= 1 ? undefined : arguments[1]);
        },
        setDisabled: function setDisabled() {
          var disabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          return _this2.setDisabled(disabled);
        },
        setHidden: function setHidden() {
          var hidden = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
          return _this2.setHidden(hidden);
        },
        isSimpleButton: function isSimpleButton() {
          return _this2.isSimpleButton();
        },
        isVisible: function isVisible() {
          var _this2$props = _this2.props,
            button = _this2$props.button,
            toolbar = _this2$props.toolbar;
          var _toolbar$calcButtonPr4 = toolbar.calcButtonProps(button),
            hidden = _toolbar$calcButtonPr4.hidden;
          return !hidden;
        }
      });
    }
  }, {
    key: "setStateProps",
    value: function setStateProps(stateKey, stateValue) {
      var _this$props2 = this.props,
        toolbar = _this$props2.toolbar,
        button = _this$props2.button;
      toolbar.setItemProps(button.originid, _defineProperty({}, stateKey, stateValue));
    }
  }, {
    key: "setDisabled",
    value: function setDisabled() {
      var disabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      this.setStateProps('disabled', disabled);
    }
  }, {
    key: "setHidden",
    value: function setHidden() {
      var hidden = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      this.setStateProps('hidden', hidden);
    }
  }, {
    key: "render",
    value: function render() {
      var _ref5;
      var _this$props3 = this.props,
        button = _this$props3.button,
        toolbar = _this$props3.toolbar,
        isMenuItem = _this$props3.isMenuItem,
        style = _this$props3.style;
      var originid = button.originid,
        children = button.children,
        onClick = button.onClick,
        getClickParams = button.getClickParams;
      var _toolbar$dev = toolbar.dev,
        iconColor = _toolbar$dev.iconColor,
        badge = _toolbar$dev.badge;
      var defaultBadge = this.state.defaultBadge;
      var _toolbar$calcButtonPr5 = toolbar.calcButtonProps(button),
        icon = _toolbar$calcButtonPr5.icon,
        text = _toolbar$calcButtonPr5.text,
        hidden = _toolbar$calcButtonPr5.hidden,
        disabled = _toolbar$calcButtonPr5.disabled,
        buttonType = _toolbar$calcButtonPr5.type,
        size = _toolbar$calcButtonPr5.size,
        buttonStyle = _toolbar$calcButtonPr5.buttonStyle;
      if (hidden) {
        return null;
      }
      var type = isMenuItem ? 'text' : buttonType;
      var btnProps = _objectSpread(_objectSpread({}, menuButtonProps), {}, {
        getClickParams: getClickParams,
        type: type,
        className: 'iup-toolbar-button',
        style: _objectSpread(_objectSpread({
          margin: "".concat(['text', 'link'].includes(type) ? 0 : '0 4px')
        }, style), buttonStyle),
        originid: originid,
        id: button.id,
        containerId: '',
        disabled: disabled,
        size: size
      });
      if (size === 'small' && ['link'].includes(type) && !btnProps.style.padding) {
        btnProps.style.padding = 0;
        btnProps.style.marginRight = 8;
      }
      var badgeText = (_ref5 = iup.isFunction(badge) ? badge(originid) : badge === null || badge === void 0 ? void 0 : badge[originid]) !== null && _ref5 !== void 0 ? _ref5 : defaultBadge;
      if (children) {
        var innerText = [text, /*#__PURE__*/_jsx(DownOutlined, {
          className: "iup-btn-icon",
          style: _objectSpread({
            marginLeft: 5
          }, iconColor ? {
            color: iconColor
          } : {})
        }, "DownOutlined")];
        return /*#__PURE__*/_jsx(Dropdown, {
          menu: {
            items: getMenuItems(toolbar, children),
            className: iup.classNames('iup-toolbar-menu', size)
          },
          disabled: disabled,
          onOpenChange: toolbar.onOpenChange(this),
          children: this.isSimpleButton() ? /*#__PURE__*/_jsx(TooltipButton, {
            title: innerText,
            badgeText: badgeText,
            buttonProps: btnProps,
            outRef: this.outRef
          }) : /*#__PURE__*/_jsx(Button, _objectSpread(_objectSpread({}, btnProps), {}, {
            children: innerText
          }))
        });
      } else if (iup.isString(text) || icon) {
        btnProps.icon = createIcon(icon, {
          className: 'iup-btn-icon',
          style: _objectSpread({}, iconColor ? {
            color: iconColor
          } : {})
        });
      }
      if (this.isSimpleButton()) {
        return /*#__PURE__*/_jsx(TooltipButton, {
          title: text,
          badgeText: badgeText,
          outRef: this.outRef,
          buttonProps: _objectSpread(_objectSpread({}, btnProps), {}, {
            onClick: onClick,
            style: _objectSpread(_objectSpread({}, btnProps.style), {}, {
              minWidth: 30
            })
          })
        });
      }
      if (iup.isReactElement(text)) {
        return /*#__PURE__*/_jsx("div", {
          style: _objectSpread(_objectSpread({
            margin: 0
          }, style), buttonStyle),
          children: /*#__PURE__*/React.cloneElement(text, {
            disabled: disabled
          })
        });
      }
      badgeText = badgeText ? /*#__PURE__*/_jsx(Badge, {
        count: badgeText,
        size: "small",
        styles: {
          root: {
            color: 'inherit'
          }
        },
        offset: [isMenuItem ? 5 : size === 'small' ? 3 : 5, size === 'small' ? -2 : -6],
        children: text
      }) : text;
      return /*#__PURE__*/_jsx(Button, _objectSpread(_objectSpread({
        ref: this.outRef
      }, btnProps), {}, {
        onClick: onClick,
        children: badgeText
      }));
    }
  }]);
  return ToolBarItem;
}(IUPComponent);
export var ToolBar = compHoc( /*#__PURE__*/function (_IUPComponent2) {
  _inherits(_class2, _IUPComponent2);
  var _super2 = _createSuper(_class2);
  function _class2(props) {
    var _this3;
    _classCallCheck(this, _class2);
    _this3 = _super2.call(this, props);
    _defineProperty(_assertThisInitialized(_this3), "_itemMap", new Map());
    _defineProperty(_assertThisInitialized(_this3), "randomKey", '');
    _defineProperty(_assertThisInitialized(_this3), "mountButtons", []);
    _defineProperty(_assertThisInitialized(_this3), "divRef", /*#__PURE__*/React.createRef());
    _defineProperty(_assertThisInitialized(_this3), "userComponents", {});
    _defineProperty(_assertThisInitialized(_this3), "dev", {});
    _defineProperty(_assertThisInitialized(_this3), "direction", {
      left: 'left',
      right: 'left'
    });
    //  justifyContent right 滚动条宽度有问题
    _defineProperty(_assertThisInitialized(_this3), "getAffixTarget", function () {
      var _this3$divRef$current;
      return iup.closest((_this3$divRef$current = _this3.divRef.current) === null || _this3$divRef$current === void 0 ? void 0 : _this3$divRef$current.parentNode, function (el) {
        return el.scrollWidth > el.offsetWidth || el.scrollHeight > el.offsetHeight;
      }) || window;
    });
    _this3.randomKey = props.id || Math.random().toString(36).slice(2);
    _this3.state = {
      affixed: false,
      dropdown: [],
      rights: {
        disableBtn: [],
        hideBtn: []
      }
    };
    return _this3;
  }
  _createClass(_class2, [{
    key: "componentDidMount",
    value: function () {
      var _componentDidMount2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
        var _this4 = this,
          _iup$getPageInstance2,
          _iup$getPageInstance3;
        var _iup$getPageInstance, _iup$getPageInstance$;
        return _regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              this.mountButtons = _toConsumableArray(this.props.buttons);
              if (this.props.rightName) {
                (_iup$getPageInstance = iup.getPageInstance()) === null || _iup$getPageInstance === void 0 || (_iup$getPageInstance$ = _iup$getPageInstance.subscribeButtonRights) === null || _iup$getPageInstance$ === void 0 || _iup$getPageInstance$.call(_iup$getPageInstance, function (rights) {
                  _this4.setState(function (prev) {
                    return _objectSpread(_objectSpread({}, prev), {}, {
                      rights: rights
                    });
                  });
                }, this.props.rightName);
              }
              (_iup$getPageInstance2 = iup.getPageInstance()) === null || _iup$getPageInstance2 === void 0 || (_iup$getPageInstance3 = _iup$getPageInstance2.subscribeButtonRights) === null || _iup$getPageInstance3 === void 0 || _iup$getPageInstance3.call(_iup$getPageInstance2, function (_ref6) {
                var replace = _ref6.replace,
                  rights = _objectWithoutProperties(_ref6, _excluded);
                _this4.setState(function (prev) {
                  if (replace) {
                    return _objectSpread(_objectSpread({}, prev), {}, {
                      rights: rights
                    });
                  }
                  var _prev$rights = prev.rights,
                    _prev$rights$disableB = _prev$rights.disableBtn,
                    disableBtn = _prev$rights$disableB === void 0 ? [] : _prev$rights$disableB,
                    _prev$rights$hideBtn = _prev$rights.hideBtn,
                    hideBtn = _prev$rights$hideBtn === void 0 ? [] : _prev$rights$hideBtn;
                  var _rights$disableBtn = rights.disableBtn,
                    nd = _rights$disableBtn === void 0 ? [] : _rights$disableBtn,
                    _rights$hideBtn = rights.hideBtn,
                    nh = _rights$hideBtn === void 0 ? [] : _rights$hideBtn;
                  return _objectSpread(_objectSpread({}, prev), {}, {
                    rights: {
                      disableBtn: _toConsumableArray(new Set([].concat(_toConsumableArray(disableBtn), _toConsumableArray(nd)))),
                      hideBtn: _toConsumableArray(new Set([].concat(_toConsumableArray(hideBtn), _toConsumableArray(nh))))
                    }
                  });
                });
              }, '$global$');
            case 3:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function componentDidMount() {
        return _componentDidMount2.apply(this, arguments);
      }
      return componentDidMount;
    }()
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var _this$props$buttons;
      (_this$props$buttons = this.props.buttons).splice.apply(_this$props$buttons, [0, this.props.buttons.length].concat(_toConsumableArray(this.mountButtons)));
    }

    /**
     * 计算按钮属性
     * @param button
     */
  }, {
    key: "calcButtonProps",
    value: function calcButtonProps(btn) {
      var button = _objectSpread(_objectSpread({}, btn), btn.props);
      var hidden = button.hidden,
        text = button.text,
        disabled = button.disabled,
        icon = button.icon,
        _button$type = button.type,
        type = _button$type === void 0 ? this.dev.type || 'default' : _button$type,
        _button$size = button.size,
        size = _button$size === void 0 ? this.dev.size || 'middle' : _button$size,
        _button$style = button.style,
        style = _button$style === void 0 ? {} : _button$style;
      var rightKey = button.rightKey || button.originid || button.key;
      var _this$dev = this.dev,
        _this$dev$disabledKey = _this$dev.disabledKeys,
        disabledKeys = _this$dev$disabledKey === void 0 ? [] : _this$dev$disabledKey,
        _this$dev$hiddenKeys = _this$dev.hiddenKeys,
        hiddenKeys = _this$dev$hiddenKeys === void 0 ? [] : _this$dev$hiddenKeys,
        _this$dev$showIcon = _this$dev.showIcon,
        showIcon = _this$dev$showIcon === void 0 ? true : _this$dev$showIcon;
      var rights = this.state.rights;
      return {
        hidden: hidden || hiddenKeys.includes(button.originid || rightKey) || rights.hideBtn.includes(rightKey),
        text: text,
        icon: showIcon ? icon : null,
        type: type,
        size: getSize(size),
        buttonStyle: style,
        disabled: disabled || disabledKeys.includes(button.originid || rightKey) || rights.disableBtn.includes(rightKey)
      };
    }
  }, {
    key: "refreshRight",
    value: function () {
      var _refreshRight = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(params) {
        var rightName, _iup$getPageInstance4, _iup$getPageInstance5;
        return _regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              rightName = this.props.rightName;
              if (!rightName) {
                _context3.next = 3;
                break;
              }
              return _context3.abrupt("return", (_iup$getPageInstance4 = iup.getPageInstance()) === null || _iup$getPageInstance4 === void 0 || (_iup$getPageInstance5 = _iup$getPageInstance4.refreshButtonRights) === null || _iup$getPageInstance5 === void 0 ? void 0 : _iup$getPageInstance5.call(_iup$getPageInstance4, _objectSpread(_objectSpread({}, params), {}, {
                rightName: rightName
              })));
            case 3:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this);
      }));
      function refreshRight(_x) {
        return _refreshRight.apply(this, arguments);
      }
      return refreshRight;
    }()
    /**
     * 原始button数据转换成标准的button格式
     * @param button 候选key或者自定义button
     */
  }, {
    key: "format",
    value: function format(button, idx) {
      var _this5 = this;
      var tmpButton = null;
      if (iup.isReactElement(button)) {
        return button;
      }
      var isObject = iup.isObject(button);
      var itemId = isObject ? button['id'] : button;
      var find = getToolBarButton(itemId);
      if (find) {
        tmpButton = isObject ? _objectSpread(_objectSpread({}, find), button) : _objectSpread(_objectSpread({}, find), {}, {
          id: itemId
        });
      } else {
        tmpButton = isObject ? _objectSpread({}, button) : null;
      }
      if (tmpButton && tmpButton.id) {
        var _iup$getPageLang, _iup$getUser;
        var btnId = tmpButton.originId || tmpButton.id;
        var langKey = tmpButton.langKey || btnId;
        var onClickCallback = tmpButton.onClick;
        // 先取业务组定义的多语言，再取toolbar定义的多语言
        tmpButton.text = ((_iup$getPageLang = iup.getPageLang()) === null || _iup$getPageLang === void 0 ? void 0 : _iup$getPageLang[langKey]) || ((_iup$getUser = iup.getUser()) === null || _iup$getUser === void 0 || (_iup$getUser = _iup$getUser.toolbarLang) === null || _iup$getUser === void 0 ? void 0 : _iup$getUser[langKey]) || tmpButton.text;
        var getData = tmpButton.getData || this.props.getData;
        var params = {
          id: btnId,
          key: btnId,
          containerId: this.props.containerId || this.getId(),
          text: tmpButton.text,
          toolbar: this,
          getData: getData,
          origin: {
            icon: tmpButton.icon,
            text: tmpButton.text,
            hidden: !!tmpButton.hidden
          }
        };
        tmpButton.onClick = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
          return _regeneratorRuntime().wrap(function _callee4$(_context4) {
            while (1) switch (_context4.prev = _context4.next) {
              case 0:
                _context4.next = 2;
                return handleClick(_objectSpread(_objectSpread({}, params), {}, {
                  onClick: onClickCallback || _this5.props.onClick,
                  button: tmpButton
                }));
              case 2:
                return _context4.abrupt("return", _context4.sent);
              case 3:
              case "end":
                return _context4.stop();
            }
          }, _callee4);
        }));
        if (onClickCallback) {
          tmpButton.getClickParams = function () {
            return _objectSpread({}, params);
          };
        }
        tmpButton.id = idx === undefined ? btnId : this.randomKey + '$' + btnId + idx;
        tmpButton.originid = btnId;
        if (!tmpButton.type && this.props.type) {
          tmpButton.type = this.props.type;
        }
      }
      return tmpButton;
    }

    /**
     * 查找原始props.button对象
     * @param originId 定义的id
     */
  }, {
    key: "findOriginItem",
    value: function findOriginItem(originId) {
      return this.dev.buttons.find(function (btn) {
        return btn.id === originId || btn === originId;
      });
    }
  }, {
    key: "findItem",
    value: function findItem(itemId) {
      var _this6 = this;
      var item = this.dev.buttons.find(function (btn, idx) {
        var id = _this6.randomKey + '$' + (iup.isString(btn) ? btn : btn.id) + idx;
        return id === itemId;
      });
      return item;
    }

    /**
     * 保存button实例的映射，方便查找button
     * @param item button实例
     */
  }, {
    key: "addItemMap",
    value: function addItemMap(item) {
      this._itemMap.set(item.props.button.originid, item);
    }

    /**
     * 删除button实例的映射，button销毁时调用
     * @param item button实例
     */
  }, {
    key: "deleteItemMap",
    value: function deleteItemMap(item) {
      this._itemMap.delete(item.props.button.originid);
    }

    /**
     * 获取button实例
     * @param itemId button的id
     */
  }, {
    key: "getItem",
    value: function getItem(itemId) {
      var _this$_itemMap$get;
      return (_this$_itemMap$get = this._itemMap.get(itemId)) === null || _this$_itemMap$get === void 0 ? void 0 : _this$_itemMap$get.getApi();
    }

    /**
     * 获取toolbar的按钮权限数据（服务端返回）
     */
  }, {
    key: "getRights",
    value: function getRights() {
      return this.state.rights;
    }

    /**
     * 动态设置button的属性
     * @param itemId  button的id
     * @param props {icon, text, hidden}
     */
  }, {
    key: "setItemProps",
    value: function setItemProps(itemId, props) {
      iup.fastDp.toolbar.updateItems({
        id: this.getId(),
        items: [_objectSpread({
          id: itemId
        }, props)]
      });
    }

    /**
     * 设置button可见
     * @param itemId button的id
     */
  }, {
    key: "showButton",
    value: function showButton(itemId) {
      this.setItemProps(itemId, {
        hidden: false
      });
    }

    /**
     * 设置button不可见
     * @param itemId button的id
     */
  }, {
    key: "hideButton",
    value: function hideButton(itemId) {
      this.setItemProps(itemId, {
        hidden: true
      });
    }
  }, {
    key: "setHidden",
    value: function setHidden(itemId) {
      var hidden = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
      this.setItemProps(itemId, {
        hidden: hidden
      });
    }
  }, {
    key: "setReadOnly",
    value: function setReadOnly(itemId) {
      var disabled = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
      this.setItemProps(itemId, {
        disabled: disabled
      });
    }

    /**
     * 获取当前的buttons
     */
  }, {
    key: "getButtons",
    value: function getButtons() {
      return this.dev.buttons;
    }

    /**
     * 动态添加button
     * @param button
     * @param index
     */
  }, {
    key: "insert",
    value: function insert(button) {
      var index = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1;
      if (!iup.isArray(button)) {
        button = [button];
      }
      iup.fastDp.toolbar.addItems({
        id: this.getId(),
        items: button,
        insertIndex: index
      });
    }

    /**
     * 删除button
     * @param ids buttonItem的id集合
     */
  }, {
    key: "delete",
    value: function _delete(ids) {
      if (!iup.isArray(ids)) {
        ids = [ids];
      }
      iup.fastDp.toolbar.deleteItems({
        id: this.getId(),
        items: ids
      });
    }

    /**
     * 设置buttons
     * @param handler 处理事件
     */
  }, {
    key: "setButtons",
    value: function setButtons(handler) {
      iup.fastDp.toolbar.setItems({
        id: this.getId(),
        items: handler
      });
    }
  }, {
    key: "subscribe",
    value: function subscribe(fn, type, buttonId) {
      if (buttonId && buttonId.length > 0) {
        var arr = iup.isArray(buttonId) ? buttonId : [buttonId];
        return this.innerSubscribe(fn, type, function (_ref8) {
          var args = _ref8.args;
          return arr.includes(args[0].id);
        });
      } else {
        return this.innerSubscribe(fn, type);
      }
    }
  }, {
    key: "onOpenChange",
    value: function onOpenChange(btn) {
      var _this7 = this;
      return function (open) {
        var _this7$dev$onOpenChan, _this7$dev;
        (_this7$dev$onOpenChan = (_this7$dev = _this7.dev).onOpenChange) === null || _this7$dev$onOpenChan === void 0 || _this7$dev$onOpenChan.call(_this7$dev, open, btn);
      };
    }
  }, {
    key: "render",
    value: function render() {
      return /*#__PURE__*/_jsx(InnerToolbar, {
        ins: this
      });
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(nextProps, prevState) {
      var newState = IUPComponent.propsToState(nextProps, prevState, ['buttons']);
      if (newState !== null && newState !== void 0 && newState.hasOwnProperty('buttons')) {
        return _objectSpread(_objectSpread({}, newState), {}, {
          dropdown: []
        });
      }
      return newState;
    }
  }]);
  return _class2;
}(IUPComponent), 'ToolBar');
function InnerToolbar(_ref9) {
  var ins = _ref9.ins;
  var _ins$state = ins.state,
    dropdown = _ins$state.dropdown,
    items = _ins$state.buttons,
    affixed = _ins$state.affixed;
  var _useDevState = useDevState({
      type: 'toolbar',
      id: ins.getId(),
      props: ins.props,
      items: items,
      itemKey: 'id'
    }),
    _useDevState2 = _slicedToArray(_useDevState, 2),
    props = _useDevState2[0],
    buttons = _useDevState2[1];
  var style = props.style,
    _props$affix = props.affix,
    affix = _props$affix === void 0 ? false : _props$affix,
    _props$direction = props.direction,
    direction = _props$direction === void 0 ? 'left' : _props$direction,
    _props$type = props.type,
    type = _props$type === void 0 ? 'button' : _props$type,
    _props$className = props.className,
    className = _props$className === void 0 ? '' : _props$className,
    _props$stopPropagatio = props.stopPropagation,
    stopPropagation = _props$stopPropagatio === void 0 ? true : _props$stopPropagatio;
  ins.dev = _objectSpread(_objectSpread({}, props), {}, {
    buttons: buttons
  });
  var tb = /*#__PURE__*/_jsxs("div", {
    id: ins.getId(),
    className: "iup-toolbar ".concat(type, " ").concat(className),
    ref: ins.divRef,
    onClick: function onClick(e) {
      return stopPropagation ? iup.stopPropagation(e) : void 0;
    },
    style: _objectSpread({
      display: 'flex',
      width: '100%',
      maxWidth: '100%',
      minHeight: 24,
      padding: 'var(--inner-padding, 8px) 4px',
      alignItems: 'center',
      justifyContent: ins.direction[direction] || direction,
      boxShadow: affix && affixed ? '0 10px 8px -8px #e0e0e0' : 'none',
      overflow: 'hidden'
    }, style),
    children: [direction === 'right' && /*#__PURE__*/_jsx(SpaceFlex, {}, "right_1"), buttons.map(function (btn, index) {
      var _ref10, _tmp$id;
      var tmp = ins.format(btn, index);
      var itemId = (_ref10 = (_tmp$id = tmp === null || tmp === void 0 ? void 0 : tmp.id) !== null && _tmp$id !== void 0 ? _tmp$id : tmp === null || tmp === void 0 ? void 0 : tmp.originid) !== null && _ref10 !== void 0 ? _ref10 : '';
      if (index === 0 && tmp && !iup.isReactElement(tmp) && !tmp.type) {
        tmp.type = 'primary';
      }
      if (!tmp || dropdown.some(function (d) {
        var _d$button;
        return d.itemId === itemId || ["_divider_".concat(index), "_user_component_".concat(index)].includes((_d$button = d.button) === null || _d$button === void 0 ? void 0 : _d$button.id);
      })) {
        return null;
      }
      if (iup.isReactElement(tmp)) {
        var uid = "_user_component_".concat(index);
        ins.userComponents[uid] = tmp;
        return /*#__PURE__*/_jsx(UserComponent, {
          uid: uid,
          toolbar: ins,
          children: tmp,
          type: props.type
        }, uid);
      }
      if (tmp.type === 'flex') {
        return /*#__PURE__*/_jsx(SpaceFlex, {}, tmp.id || index);
      }
      if (tmp.type === 'divider') {
        return /*#__PURE__*/_jsx(Divider, {
          type: "vertical",
          "data-cid": "_divider_".concat(index)
        }, "_divider_".concat(index));
      }
      return /*#__PURE__*/_jsx(ToolBarItem, {
        button: tmp,
        toolbar: ins
      }, tmp.id || index);
    }), /*#__PURE__*/_jsx(FoldMenu, {
      toolbar: ins
    })]
  });
  if (affix) {
    var affixConfig = iup.isObject(affix) ? affix : {};
    return /*#__PURE__*/_jsx(Affix, _objectSpread(_objectSpread({
      target: ins.getAffixTarget
    }, affixConfig), {}, {
      onChange: function onChange(affixed) {
        return ins.setState({
          affixed: affixed
        });
      },
      children: tb
    }));
  }
  return tb;
}